/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package canteen.sys.view;

import canteen.sys.model.entity.DepartmentMaster;
import canteen.sys.model.generic.HibernateDAOFactory;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;

/**
 *
 * @author TNT
 */
public class DepartmentEntry extends javax.swing.JInternalFrame implements ActionView<DepartmentMaster> {

    HibernateDAOFactory hibernateDAOFactory = HibernateDAOFactory.getInstance();
    //tat ca toi deu tap hop trong file class nay! nen chi can sd thong qua no thoi.
    DefaultTableModel modelTable;

    /**
     * Creates new form DepartmentEntry
     */
    public DepartmentEntry() {
        initComponents();
        modelTable = (DefaultTableModel) tableDepartment.getModel();
        List<DepartmentMaster> listDepartment = hibernateDAOFactory.getDepartmentMasterDAO().findAll();
        showList(listDepartment);
        listenerTableModel();
        listSelectionListener();
        hibernateDAOFactory.getDepartmentMasterDAO().findByNameAndStatus(title, isMaximum);//hieu chu?ok
         //hoi bop dai bon kia nhung chac deo gi da hieu hieu dc moi' tai` :)) minh chu yeu la hocj =) uhm nhug cung no cho no 1 chut co* ban k di bao ve ong thay hoi? code lai bao? code binh thuong thi vl day
        //ah uh phai lo mot chut chu! beginer ma!! chua doc vao! cac ong chac quai gi da map dc code ngay dau. noi hthang ra thi ong lan mom chua chac da dong toi cai nay :)) thoi tam dc roi lam gi lam di thanks
    }

    public final void listenerTableModel() {
        modelTable.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                if (e.getType() == TableModelEvent.DELETE) {
                    JOptionPane.showMessageDialog(null, "Delete Success!");
                } else if (e.getType() == TableModelEvent.INSERT) {
                    JOptionPane.showMessageDialog(null, "Add new Department Success!");
                } else if (e.getType() == TableModelEvent.UPDATE && e.getColumn() == 2) {
                    JOptionPane.showMessageDialog(null, "Update Department Success!");
                }
            }
        });
    }

    public final void listSelectionListener() {
        tableDepartment.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int rowSelected = tableDepartment.getSelectedRow();
                showDetail(getObject(rowSelected));
                btsave.setText("Update");
                btcancel.setEnabled(true);
            }
        });
    }

    @Override
    public void showDetail(DepartmentMaster department) {
        txtDepID.setText(department.getDeptId() + "");
        txtDepName.setText(department.getDepartmentName());
        rbStatus.setSelected(department.isStatus());
    }

    @Override
    public void deleteRow(int index) {

        if (modelTable.getRowCount() > 0) {
            if (index > 0) {
                tableDepartment.setRowSelectionInterval(index - 1, index - 1);
                modelTable.removeRow(index);
            } else {
                tableDepartment.setRowSelectionInterval(index + 1, index + 1);
                modelTable.removeRow(0);
            }
        } else {
            JOptionPane.showMessageDialog(this, "There is no row to delete!", "Warning!", JOptionPane.WARNING_MESSAGE);
        }
    }

    @Override
    public DepartmentMaster getObject(int index) {
        DepartmentMaster departmentMaster = new DepartmentMaster();
        boolean status = false;
        departmentMaster.setDeptId(Integer.parseInt(modelTable.getValueAt(index, 0).toString()));
        departmentMaster.setDepartmentName(modelTable.getValueAt(index, 1).toString());
        if (modelTable.getValueAt(index, 2).equals("enable")) {
            status = true;
        }
        departmentMaster.setStatus(status);
        return departmentMaster;
    }

    @Override
    public void updateRow(DepartmentMaster row, int index) {
        modelTable.setValueAt(row.getDepartmentName(), index, 1);
        if (row.isStatus()) {
            modelTable.setValueAt("enable", index, 2);
        } else {
            modelTable.setValueAt("disable", index, 2);
        }
    }

    @Override
    public void addRow(DepartmentMaster row, boolean posion) {
        String status = "disable";
        if (row.isStatus()) {
            status = "enable";
        }
        if (posion) {
            modelTable.insertRow(0, new Object[]{row.getDeptId() + "", row.getDepartmentName() + "", status});
        } else {
            modelTable.insertRow(tableDepartment.getRowCount(), new Object[]{row.getDeptId() + "", row.getDepartmentName() + "", status});
        }
    }

    @Override
    public final void showList(List<DepartmentMaster> list) {
        String status;
        for (int i = 0; i < 4; i++) {
            modelTable.removeRow(0);
        }
        for (DepartmentMaster item : list) {
            if (item.isStatus()) {
                status = "enable";
            } else {
                status = "disable";
            }
            modelTable.insertRow(0, new Object[]{item.getDeptId(), item.getDepartmentName(), status});
        }

        //setModelTable(model);
    }

    @Override
    public boolean validObject(DepartmentMaster object) {
        if (object.getDepartmentName().equals("") || object.getDepartmentName() == null) {
            JOptionPane.showMessageDialog(this, "Department Name must input!");
            return false;
        }
        return true;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btsave = new javax.swing.JButton();
        btdelete = new javax.swing.JButton();
        btcancel = new javax.swing.JButton();
        txtDepID = new javax.swing.JTextField();
        txtDepName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        rbStatus = new javax.swing.JRadioButton();
        jLayeredPane2 = new javax.swing.JLayeredPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableDepartment = new javax.swing.JTable();

        setClosable(true);
        setTitle("Department Entry");

        jLayeredPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Box"));
        jLayeredPane1.setToolTipText("");

        jLabel1.setText("Department ID");
        jLabel1.setBounds(10, 30, 130, 14);
        jLayeredPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel2.setText("Department Name");
        jLabel2.setBounds(10, 70, 130, 14);
        jLayeredPane1.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        btsave.setText("Save");
        btsave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btsaveActionPerformed(evt);
            }
        });
        btsave.setBounds(10, 140, 80, 23);
        jLayeredPane1.add(btsave, javax.swing.JLayeredPane.DEFAULT_LAYER);

        btdelete.setText("Delete");
        btdelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btdeleteActionPerformed(evt);
            }
        });
        btdelete.setBounds(110, 140, 80, 23);
        jLayeredPane1.add(btdelete, javax.swing.JLayeredPane.DEFAULT_LAYER);

        btcancel.setText("Cancel");
        btcancel.setEnabled(false);
        btcancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btcancelActionPerformed(evt);
            }
        });
        btcancel.setBounds(210, 140, 80, 23);
        jLayeredPane1.add(btcancel, javax.swing.JLayeredPane.DEFAULT_LAYER);

        txtDepID.setEnabled(false);
        txtDepID.setBounds(150, 30, 190, 20);
        jLayeredPane1.add(txtDepID, javax.swing.JLayeredPane.DEFAULT_LAYER);
        txtDepName.setBounds(150, 70, 190, 20);
        jLayeredPane1.add(txtDepName, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel3.setText("Status");
        jLabel3.setBounds(10, 100, 90, 14);
        jLayeredPane1.add(jLabel3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        rbStatus.setSelected(true);
        rbStatus.setBounds(150, 100, 21, 21);
        jLayeredPane1.add(rbStatus, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLayeredPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Click on Record to Delete or Edit"));

        tableDepartment.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Department ID", "Department Name", "Status"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tableDepartment);

        jScrollPane1.setBounds(10, 20, 340, 340);
        jLayeredPane2.add(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 359, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLayeredPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 359, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLayeredPane2)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 219, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btcancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btcancelActionPerformed
        // TODO add your handling code here:
//        DepartmentMaster departmentMaster = new DepartmentMaster();
//        departmentMaster.setDepartmentName("TNTuyen");
//        departmentMaster.setStatus(false);
//        updateRow(departmentMaster, 2);
        //this.dispose();
        btsave.setText("Save");
        btcancel.setEnabled(false);
    }//GEN-LAST:event_btcancelActionPerformed

    private void btsaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btsaveActionPerformed
        // TODO add your handling code here:
        try {
            DepartmentMaster department = new DepartmentMaster();
            if (btsave.getText().equals("Save")) {
                department.setDepartmentName(txtDepName.getText());
                department.setStatus(rbStatus.isSelected());
                validInsertDepartment(department);
            } else {
                department.setDeptId(Integer.parseInt(txtDepID.getText()));
                department.setDepartmentName(txtDepName.getText());
                department.setStatus(rbStatus.isSelected());
                validInsertDepartment(department);
                btsave.setText("Save");
                btcancel.setEnabled(false);
            }
            this.txtDepName.requestFocus();
        } catch (HibernateException ex) {
            JOptionPane.showMessageDialog(this, "Add new DepartmentEntry Fail!\n Error: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btsaveActionPerformed

    private void btdeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btdeleteActionPerformed
        // TODO add your handling code here:
        int indexRow = tableDepartment.getSelectedRow();
        if (indexRow != -1) {
            try {
                if (modelTable.getRowCount() > 1) {
                    hibernateDAOFactory.getDepartmentMasterDAO().makeTransient(getObject(indexRow));
                    deleteRow(indexRow);
                }
            } catch (HibernateException ex) {
                JOptionPane.showMessageDialog(this, "Can't delete Department\nError: " + ex.getMessage());
            }
        } else {
            JOptionPane.showMessageDialog(this, "No row selected!", "Warning", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btdeleteActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btcancel;
    private javax.swing.JButton btdelete;
    private javax.swing.JButton btsave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JLayeredPane jLayeredPane2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton rbStatus;
    private javax.swing.JTable tableDepartment;
    private javax.swing.JTextField txtDepID;
    private javax.swing.JTextField txtDepName;
    // End of variables declaration//GEN-END:variables

    private void validInsertDepartment(DepartmentMaster department) {
        if (validObject(department)) {
            DepartmentMaster departmentResult = hibernateDAOFactory.getDepartmentMasterDAO().makePersistent(department);
            showDetail(departmentResult);
            if (btsave.getText().equals("Save")) {
                addRow(department, true);
            } else {
                updateRow(department, tableDepartment.getSelectedRow());
            }
        }
    }

    @Override
    public void setObject(DepartmentMaster object) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
